{% extends 'base.html' %}

{% block title %}批量导入合同 - 固定资产管理系统{% endblock %}

{% block extra_css %}
<style>
.import-steps {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 10px;
    padding: 20px;
    margin-bottom: 30px;
}

.step-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    padding: 10px;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 8px;
    transition: all 0.3s ease;
}

.step-item:hover {
    background: rgba(255, 255, 255, 0.2);
    transform: translateX(5px);
}

.step-number {
    background: rgba(255, 255, 255, 0.3);
    border-radius: 50%;
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;
    font-weight: bold;
}

.file-upload-zone {
    border: 3px dashed #dee2e6;
    border-radius: 15px;
    padding: 40px;
    text-align: center;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    transition: all 0.3s ease;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.file-upload-zone:hover {
    border-color: #007bff;
    background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
    transform: scale(1.02);
}

.file-upload-zone.dragover {
    border-color: #28a745;
    background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
    transform: scale(1.05);
}

.upload-icon {
    font-size: 4rem;
    color: #6c757d;
    margin-bottom: 20px;
    transition: all 0.3s ease;
}

.file-upload-zone:hover .upload-icon {
    color: #007bff;
    transform: scale(1.1);
}

.progress-container {
    display: none;
    margin-top: 20px;
}

.import-result {
    display: none;
    margin-top: 20px;
}

.result-card {
    border-radius: 10px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.template-info {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
    color: white;
    border-radius: 10px;
    padding: 20px;
}

.error-list {
    max-height: 300px;
    overflow-y: auto;
}

.success-animation {
    animation: successPulse 2s ease-in-out;
}

@keyframes successPulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.05); }
    100% { transform: scale(1); }
}
</style>
{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="{% url 'assets:index' %}">首页</a></li>
                <li class="breadcrumb-item"><a href="{% url 'assets:contract_list' %}">合同管理</a></li>
                <li class="breadcrumb-item active" aria-current="page">批量导入合同</li>
            </ol>
        </nav>
        
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-file-import me-2"></i>批量导入合同</h2>
            <div class="btn-group">
                <a href="{% url 'assets:contract_list' %}" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left me-1"></i>返回列表
                </a>
                <a href="{% url 'assets:contract_create' %}" class="btn btn-outline-primary">
                    <i class="fas fa-plus me-1"></i>新增合同
                </a>
            </div>
        </div>

        <!-- 导入步骤说明 -->
        <div class="import-steps">
            <h4 class="mb-3"><i class="fas fa-list-ol me-2"></i>导入步骤</h4>
            <div class="step-item">
                <div class="step-number">1</div>
                <div>
                    <strong>下载模板</strong>
                    <p class="mb-0">点击下方按钮下载Excel导入模板，了解数据格式要求</p>
                </div>
            </div>
            <div class="step-item">
                <div class="step-number">2</div>
                <div>
                    <strong>填写数据</strong>
                    <p class="mb-0">按照模板格式填写合同信息，确保数据完整准确</p>
                </div>
            </div>
            <div class="step-item">
                <div class="step-number">3</div>
                <div>
                    <strong>上传文件</strong>
                    <p class="mb-0">将填写好的Excel文件拖拽到下方区域或点击选择文件</p>
                </div>
            </div>
            <div class="step-item">
                <div class="step-number">4</div>
                <div>
                    <strong>确认导入</strong>
                    <p class="mb-0">系统验证数据后，确认导入结果并处理可能的错误</p>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- 左侧：模板下载和说明 -->
            <div class="col-md-4">
                <div class="template-info">
                    <h5><i class="fas fa-download me-2"></i>模板下载</h5>
                    <p>请先下载标准模板，按照格式要求填写合同信息。</p>
                    <a href="{% url 'assets:download_import_template' 'contracts' %}" class="btn btn-light btn-lg w-100">
                        <i class="fas fa-file-excel me-2"></i>下载Excel模板
                    </a>
                </div>

                <div class="card mt-4">
                    <div class="card-header">
                        <h6 class="mb-0"><i class="fas fa-info-circle me-2"></i>注意事项</h6>
                    </div>
                    <div class="card-body">
                        <ul class="list-unstyled mb-0">
                            <li class="mb-2">
                                <i class="fas fa-check text-success me-2"></i>
                                <small>合同名称为必填项</small>
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-check text-success me-2"></i>
                                <small>合同编号需要唯一</small>
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-check text-success me-2"></i>
                                <small>供应商名称必须存在</small>
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-check text-success me-2"></i>
                                <small>日期格式为 YYYY-MM-DD</small>
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-check text-success me-2"></i>
                                <small>支持Excel (.xlsx) 格式</small>
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-check text-success me-2"></i>
                                <small>单次最多导入500条记录</small>
                            </li>
                        </ul>
                    </div>
                </div>

                <div class="card mt-3">
                    <div class="card-header">
                        <h6 class="mb-0"><i class="fas fa-table me-2"></i>字段说明</h6>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>字段</th>
                                        <th>必填</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>合同名称</td>
                                        <td><span class="badge bg-danger">是</span></td>
                                    </tr>
                                    <tr>
                                        <td>合同编号</td>
                                        <td><span class="badge bg-danger">是</span></td>
                                    </tr>
                                    <tr>
                                        <td>合同类型</td>
                                        <td><span class="badge bg-secondary">否</span></td>
                                    </tr>
                                    <tr>
                                        <td>供应商名称</td>
                                        <td><span class="badge bg-danger">是</span></td>
                                    </tr>
                                    <tr>
                                        <td>开始日期</td>
                                        <td><span class="badge bg-danger">是</span></td>
                                    </tr>
                                    <tr>
                                        <td>结束日期</td>
                                        <td><span class="badge bg-danger">是</span></td>
                                    </tr>
                                    <tr>
                                        <td>合同金额</td>
                                        <td><span class="badge bg-danger">是</span></td>
                                    </tr>
                                    <tr>
                                        <td>合同状态</td>
                                        <td><span class="badge bg-secondary">否</span></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 右侧：文件上传 -->
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-cloud-upload-alt me-2"></i>文件上传</h5>
                    </div>
                    <div class="card-body">
                        <form id="importForm" method="post" enctype="multipart/form-data">
                            {% csrf_token %}
                            
                            <div class="file-upload-zone" id="uploadZone" onclick="document.getElementById('excelFile').click()">
                                <div class="upload-icon">
                                    <i class="fas fa-cloud-upload-alt"></i>
                                </div>
                                <h4>点击选择文件或拖拽到此处</h4>
                                <p class="text-muted mb-0">支持 .xlsx 格式，文件大小不超过 10MB</p>
                                <p class="text-muted">请确保使用标准模板格式</p>
                            </div>
                            
                            <input type="file" id="excelFile" name="excel_file" accept=".xlsx,.xls" style="display: none;">
                            
                            <!-- 文件信息显示 -->
                            <div id="fileInfo" style="display: none;" class="mt-3">
                                <div class="alert alert-info">
                                    <div class="d-flex align-items-center">
                                        <i class="fas fa-file-excel fa-2x me-3 text-success"></i>
                                        <div class="flex-grow-1">
                                            <h6 class="mb-1" id="fileName"></h6>
                                            <small class="text-muted" id="fileSize"></small>
                                        </div>
                                        <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeFile()">
                                            <i class="fas fa-times"></i> 移除
                                        </button>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 进度条 -->
                            <div class="progress-container">
                                <div class="progress mb-3">
                                    <div class="progress-bar progress-bar-striped progress-bar-animated" 
                                         role="progressbar" style="width: 0%"></div>
                                </div>
                                <div class="text-center">
                                    <span class="progress-text">准备上传...</span>
                                </div>
                            </div>
                            
                            <!-- 提交按钮 -->
                            <div class="text-center mt-4">
                                <button type="submit" id="submitBtn" class="btn btn-success btn-lg" disabled>
                                    <i class="fas fa-upload me-2"></i>开始导入
                                </button>
                                <button type="button" class="btn btn-outline-secondary btn-lg ms-2" onclick="resetForm()">
                                    <i class="fas fa-undo me-2"></i>重置
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- 导入结果 -->
                <div class="import-result">
                    <div class="card result-card mt-4">
                        <div class="card-header">
                            <h5 class="mb-0"><i class="fas fa-chart-bar me-2"></i>导入结果</h5>
                        </div>
                        <div class="card-body">
                            <div class="row text-center mb-3">
                                <div class="col-md-3">
                                    <div class="card bg-primary text-white">
                                        <div class="card-body">
                                            <h4 class="mb-0" id="totalCount">0</h4>
                                            <small>总记录数</small>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="card bg-success text-white">
                                        <div class="card-body">
                                            <h4 class="mb-0" id="successCount">0</h4>
                                            <small>成功导入</small>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="card bg-warning text-white">
                                        <div class="card-body">
                                            <h4 class="mb-0" id="skipCount">0</h4>
                                            <small>跳过记录</small>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="card bg-danger text-white">
                                        <div class="card-body">
                                            <h4 class="mb-0" id="errorCount">0</h4>
                                            <small>错误记录</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 错误详情 -->
                            <div id="errorDetails" style="display: none;">
                                <h6><i class="fas fa-exclamation-triangle me-2 text-warning"></i>错误详情</h6>
                                <div class="error-list">
                                    <div class="table-responsive">
                                        <table class="table table-sm table-striped">
                                            <thead>
                                                <tr>
                                                    <th>行号</th>
                                                    <th>合同名称</th>
                                                    <th>错误信息</th>
                                                </tr>
                                            </thead>
                                            <tbody id="errorTableBody">
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 操作按钮 -->
                            <div class="text-center mt-3">
                                <a href="{% url 'assets:contract_list' %}" class="btn btn-primary">
                                    <i class="fas fa-list me-2"></i>查看合同列表
                                </a>
                                <button type="button" class="btn btn-outline-secondary ms-2" onclick="resetImport()">
                                    <i class="fas fa-redo me-2"></i>重新导入
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let selectedFile = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeFileUpload();
});

// 初始化文件上传功能
function initializeFileUpload() {
    const uploadZone = document.getElementById('uploadZone');
    const fileInput = document.getElementById('excelFile');
    
    // 拖拽事件
    uploadZone.addEventListener('dragover', function(e) {
        e.preventDefault();
        this.classList.add('dragover');
    });
    
    uploadZone.addEventListener('dragleave', function(e) {
        e.preventDefault();
        this.classList.remove('dragover');
    });
    
    uploadZone.addEventListener('drop', function(e) {
        e.preventDefault();
        this.classList.remove('dragover');
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            handleFileSelect(files[0]);
        }
    });
    
    // 文件选择事件
    fileInput.addEventListener('change', function(e) {
        if (e.target.files.length > 0) {
            handleFileSelect(e.target.files[0]);
        }
    });
    
    // 表单提交事件
    document.getElementById('importForm').addEventListener('submit', function(e) {
        e.preventDefault();
        if (selectedFile) {
            startImport();
        }
    });
}

// 处理文件选择
function handleFileSelect(file) {
    // 验证文件类型
    const allowedTypes = [
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/vnd.ms-excel'
    ];
    
    if (!allowedTypes.includes(file.type)) {
        alert('请选择Excel文件 (.xlsx 或 .xls)');
        return;
    }
    
    // 验证文件大小 (10MB)
    if (file.size > 10 * 1024 * 1024) {
        alert('文件大小不能超过10MB');
        return;
    }
    
    selectedFile = file;
    
    // 显示文件信息
    document.getElementById('fileName').textContent = file.name;
    document.getElementById('fileSize').textContent = formatFileSize(file.size);
    document.getElementById('fileInfo').style.display = 'block';
    document.getElementById('submitBtn').disabled = false;
    
    // 隐藏上传区域
    document.getElementById('uploadZone').style.display = 'none';
}

// 移除文件
function removeFile() {
    selectedFile = null;
    document.getElementById('fileInfo').style.display = 'none';
    document.getElementById('uploadZone').style.display = 'block';
    document.getElementById('submitBtn').disabled = true;
    document.getElementById('excelFile').value = '';
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 开始导入
function startImport() {
    const progressContainer = document.querySelector('.progress-container');
    const progressBar = document.querySelector('.progress-bar');
    const progressText = document.querySelector('.progress-text');
    const submitBtn = document.getElementById('submitBtn');
    
    // 显示进度条
    progressContainer.style.display = 'block';
    submitBtn.disabled = true;
    
    // 创建FormData
    const formData = new FormData();
    formData.append('excel_file', selectedFile);
    formData.append('csrfmiddlewaretoken', document.querySelector('[name=csrfmiddlewaretoken]').value);
    
    // 模拟进度更新
    let progress = 0;
    const progressInterval = setInterval(() => {
        progress += Math.random() * 15;
        if (progress > 90) progress = 90;
        progressBar.style.width = progress + '%';
        progressText.textContent = '正在处理数据...';
    }, 200);
    
    // 发送请求
    fetch('{% url "assets:contract_bulk_import" %}', {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.json())
    .then(data => {
        clearInterval(progressInterval);
        progressBar.style.width = '100%';
        progressText.textContent = '导入完成！';
        
        setTimeout(() => {
            progressContainer.style.display = 'none';
            showImportResult(data);
        }, 1000);
    })
    .catch(error => {
        clearInterval(progressInterval);
        progressContainer.style.display = 'none';
        submitBtn.disabled = false;
        alert('导入过程中发生错误：' + error.message);
    });
}

// 显示导入结果
function showImportResult(data) {
    document.getElementById('totalCount').textContent = data.total || 0;
    document.getElementById('successCount').textContent = data.success || 0;
    document.getElementById('skipCount').textContent = data.skip || 0;
    document.getElementById('errorCount').textContent = data.error || 0;
    
    // 显示错误详情
    if (data.errors && data.errors.length > 0) {
        const errorTableBody = document.getElementById('errorTableBody');
        errorTableBody.innerHTML = '';
        
        data.errors.forEach(error => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${error.row}</td>
                <td>${error.name || '-'}</td>
                <td class="text-danger">${error.message}</td>
            `;
            errorTableBody.appendChild(row);
        });
        
        document.getElementById('errorDetails').style.display = 'block';
    }
    
    // 显示结果区域
    document.querySelector('.import-result').style.display = 'block';
    document.querySelector('.result-card').classList.add('success-animation');
    
    // 滚动到结果区域
    document.querySelector('.import-result').scrollIntoView({ behavior: 'smooth' });
}

// 重置表单
function resetForm() {
    if (confirm('确定要重置表单吗？')) {
        removeFile();
        document.querySelector('.progress-container').style.display = 'none';
        document.querySelector('.import-result').style.display = 'none';
        document.getElementById('submitBtn').disabled = true;
    }
}

// 重新导入
function resetImport() {
    document.querySelector('.import-result').style.display = 'none';
    removeFile();
}
</script>
{% endblock %}